package com.example.springsecurity.utils;

import cn.hutool.captcha.generator.RandomGenerator;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.example.springsecurity.pojo.SMSModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class SMSUtil {
    @Autowired
    private SMSModel smsModel;
    @Autowired
    private RedisTemplate redisTemplate;
    public String generateSms(String phone) {
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsModel.getAccountId();
        String accountToken = smsModel.getAuthToken();
        //请使用管理控制台中已创建应用的APPID
        String appId = smsModel.getAppId();
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId= "1";//免费模板id为1

        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        String randomNum = randomGenerator.generate();//4位随机数
        Long expire=2l;//有效期

        String[] datas = {randomNum, expire.toString()};
        //发送短信
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        if("000000".equals(result.get("statusCode"))){
            //验证码存入redis，设置有效期30s
            redisTemplate.opsForValue().set(phone,randomNum);
            redisTemplate.expire(phone,60L, TimeUnit.SECONDS);

            return randomNum;
        }else{
           return null;
        }
    }




    public boolean validateSms(String phone, String sms) {
        if (phone == null) {
            throw new IllegalArgumentException("Phone number cannot be null");
        }
        //取得redis中的验证码
        Object obj = redisTemplate.opsForValue().get(phone);
        if(Objects.isNull(obj)){
            return false;
        }
        String sms_redis = (String)obj;

        return sms_redis.equalsIgnoreCase(sms);
    }

}
